package com.cbn.ibcp.web.jishiting.operator.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.cbn.ibcp.common.annotation.Log;
import com.cbn.ibcp.common.core.domain.Result;
import com.cbn.ibcp.common.enums.BusinessType;
import com.cbn.ibcp.jishiting.gs.cms.domain.CpVideo;
import com.cbn.ibcp.jishiting.gs.cms.domain.Node;
import com.cbn.ibcp.jishiting.gs.cms.domain.Org;
import com.cbn.ibcp.jishiting.gs.cms.service.ICpVideoService;
import com.cbn.ibcp.jishiting.gs.cms.service.INodeService;
import com.cbn.ibcp.jishiting.gs.cms.service.IOrgService;
import com.cbn.ibcp.jishiting.rms.domain.ResBase;
import com.cbn.ibcp.jishiting.rms.domain.ResBasePlayConfig;
import com.cbn.ibcp.jishiting.rms.domain.ResCp;
import com.cbn.ibcp.jishiting.rms.domain.ResourceStream;
import com.cbn.ibcp.jishiting.rms.service.IResBasePlayConfigService;
import com.cbn.ibcp.jishiting.rms.service.IResBaseService;
import com.cbn.ibcp.jishiting.rms.service.IResCpService;
import com.cbn.ibcp.jishiting.rms.service.IResourceStreamService;
import com.cbn.ibcp.web.client.GsCmsClient;
import com.cbn.ibcp.web.client.dto.CpVideoDTO;
import com.cbn.ibcp.web.common.config.GsCmsConfig;
import com.cbn.ibcp.web.init.LoadDatasource;
import com.cbn.ibcp.web.jishiting.operator.vo.OrgVO;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/gsCms")
@RequiredArgsConstructor
public class GsCmsController {

    private static final String DELETE_CONTENT_XML_TEMPLATE = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><DeleteContent album_id=\"{albumId}\" video_id=\"{videoId}\" del_type=\"{delType}\" reasonCode=\"200\"> <orgList> <org code=\"{orgCode}\"/></orgList></DeleteContent>";


    private final GsCmsClient gsCmsClient;


    private final IResBaseService resBaseService;

    private final IResCpService resCpService;

    private final IResBasePlayConfigService resBasePlayConfigService;

    private final ICpVideoService cpVideoService;


    private final IResourceStreamService resourceStreamService;


    private final IOrgService orgService;

    private final INodeService nodeService;

    @PreAuthorize("@ss.hasAnyPermi('jishiting:rms:resourcestream:origin:province:videodelete')")
    @Log(title = "批量分省删除", businessType = BusinessType.DELETE)
    @GetMapping("/deleteOriginResourceStreamOrgData")
    public Result<String> deleteOriginResourceStreamOrgData(String orgCodesStr, String albumId, String videoId) {
        if (Objects.isNull(albumId) || Objects.isNull(videoId)) {
            return Result.fail("参数错误");
        }
        CpVideo cpVideo = cpVideoService.getByVideoId(videoId);
        if (cpVideo == null) {
            return Result.fail("视频不存在");
        }
        Long albumIdLong = Long.parseLong(cpVideo.getAlbumId());
        Long videoIdLong = Long.parseLong(cpVideo.getVideoId());
        //查询注入省份
        List<ResBase> resBaseList = resBaseService.getListByIdListAndResTypeList(ListUtil.toList(videoIdLong), ListUtil.toList(1, 21));
        if (CollectionUtil.isEmpty(resBaseList)) {
            return Result.ok("未找到资源");
        }
        ResBase resBase = resBaseList.get(0);
        Long contentProviderId = resBase.getContentProviderId();
        ResCp resCp = resCpService.getById(contentProviderId);
        String code = resCp.getCode();
        List<ResBasePlayConfig> resBasePlayConfigList = resBasePlayConfigService.getListByCpCode(code);
        if (CollectionUtil.isEmpty(resBasePlayConfigList)) {
            return Result.ok("未找到分省配置");
        }
        List<String> orgCodeList = resBasePlayConfigList.stream().map(ResBasePlayConfig::getOrgCode).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(orgCodeList)) {
            return Result.ok("未找到分省编码");
        }
        List<String> orgCodes = null;
        if (StrUtil.isNotBlank(orgCodesStr)) {
            orgCodes = StrUtil.split(orgCodesStr, ",");
        }
        if (CollectionUtil.isNotEmpty(orgCodes)) {
            orgCodeList = orgCodeList.stream().filter(Objects::nonNull).filter(orgCodes::contains).collect(Collectors.toList());
        }
        orgCodeList = orgCodeList.stream().filter(orgCode -> !LoadDatasource.notInjectOrgCodeList.contains(orgCode)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(orgCodeList)) {
            return Result.ok("未找到分省编码");
        }
        Integer resType = resBase.getResType();
        orgCodeList.forEach(orgCode -> {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orgCode", orgCode);
            if (resType == 1) {
                dataMap.put("albumId", videoIdLong);
            } else {
                dataMap.put("albumId", albumIdLong);
            }
            dataMap.put("videoId", videoIdLong);
            dataMap.put("delType", 1);
            String deleteContentXml = StrUtil.format(DELETE_CONTENT_XML_TEMPLATE, dataMap);
            gsCmsClient.deleteContentAction(deleteContentXml);
        });
        return Result.ok(null);
    }


    @PreAuthorize("@ss.hasAnyPermi('jishiting:rms:resourcestream:province:videodelete,jishiting:rms:resourcestreamorg:province:videodelete')")
    @GetMapping("/deleteResourceStreamOrgData")
    public Result<String> deleteResourceStreamOrgData(String orgCode, String albumId, String videoId, Integer resType) {
        if (StrUtil.isBlank(orgCode) || StrUtil.isBlank(albumId) || StrUtil.isBlank(videoId) || Objects.isNull(resType)) {
            return Result.fail("参数错误");
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("orgCode", orgCode);
        CpVideo cpVideo = cpVideoService.getByVideoId(videoId);
        if (Objects.isNull(cpVideo)) {
            return Result.fail("未找到该资源");
        }
        dataMap.put("albumId", cpVideo.getAlbumId());
        dataMap.put("videoId", cpVideo.getVideoId());
        dataMap.put("delType", 1);
        String deleteContentXml = StrUtil.format(DELETE_CONTENT_XML_TEMPLATE, dataMap);
        String result = gsCmsClient.deleteContentAction(deleteContentXml);
        return Result.ok(result);
    }


    @PreAuthorize("@ss.hasAnyPermi('jishiting:rms:resourcestream:origin:recreatetsfile')")
    @GetMapping("/recreateTsFile")
    public Result<Boolean> recreateTsFile(String id, String albumId, String videoId, Integer quality) {
        if (StrUtil.isBlank(id)) {
            return Result.fail("参数错误");
        }
        if (StrUtil.isBlank(albumId) || StrUtil.isBlank(videoId)) {
            return Result.fail("参数错误");
        }
        Long albumIdLong = Long.parseLong(albumId);
        Long videoIdLong = Long.parseLong(videoId);
        Long idLong = Long.parseLong(id);
        ResourceStream resourceStream = resourceStreamService.selectById(idLong);
        if (resourceStream == null) {
            return Result.fail("未找到记录");
        }
        if (!resourceStream.getResId().equals(videoIdLong) || !resourceStream.getQuality().equals(quality)) {
            return Result.fail("参数错误");
        }
        List<CpVideo> cpVideos = cpVideoService.getListByParam(albumIdLong, videoIdLong);
        if (CollUtil.isEmpty(cpVideos)) {
            return Result.fail("未找到记录");
        }
        if (cpVideos.size() > 1) {
            return Result.fail("请选择一条记录");
        }
        CpVideo cpVideo = cpVideos.get(0);
        CpVideoDTO cpVideoDTO = new CpVideoDTO();
        cpVideoDTO.setId(cpVideo.getId());
        return gsCmsClient.fixedTsFileNotExist(cpVideoDTO);
    }


    @GetMapping("/selectEnableOrgCodeList")
    public Result<List<OrgVO>> selectEnableOrgCodeList() {
        List<Org> orgs = orgService.selectList();
        List<Node> nodes = nodeService.selectList();
        if (CollectionUtil.isEmpty(orgs)) {
            return null;
        }
        List<OrgVO> orgVOS = new ArrayList<>();
        Map<Long, Org> orgMap = orgs.stream().collect(Collectors.toMap(Org::getId, org -> org, (org1, org2) -> org1));
        List<String> cdnOrgCodeList = GsCmsConfig.cdnOrgCodeList;
        nodes.forEach(node -> {
            OrgVO orgVO = new OrgVO();
            Org org = orgMap.get(node.getOrgIdx());
            if (org != null && cdnOrgCodeList.contains(org.getCode())) {
                orgVO.setId(org.getId());
                orgVO.setName(org.getName());
                orgVO.setCode(org.getCode());
                orgVOS.add(orgVO);
            }
        });
        return Result.ok(orgVOS);
    }
}
